package com.hbnu.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author kittychen
 * @since 2025-11-04 15:13
 */
@WebServlet("/cookieDemo01")
public class CookieDemo01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        // 获取所有的Cookie
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("visitedTime".equals(cookie.getName())) {
                    Long time = Long.valueOf(cookie.getValue());
                    Date date = new Date(time);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format = simpleDateFormat.format(date);
                    resp.getWriter().println("欢迎回来，上次访问时间为：" + format);
                }
                if ("username".equals(cookie.getName())) {
                    resp.getWriter().println("欢迎回来，用户名为：" + cookie.getValue());
                }
            }
        } else {
            resp.getWriter().println("欢迎首次访问");
        }

        // 1.创建Cookie对象
        Cookie cookie = new Cookie("visitedTime", System.currentTimeMillis() + "");
        Cookie cookie1 = new Cookie("username", "kittychen");

        // 设置Cookie的存活时间
        // cookie.setMaxAge(60 * 60 * 24);   // 存活一天

        // 2.发送Cookie
        resp.addCookie(cookie);
        resp.addCookie(cookie1);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
